package com.dsunsoft.rtu.core.oauth.config;

import com.dsunsoft.rtu.properties.OAuthProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.provisioning.UserDetailsManager;

/**
 * SecurityConfig<br/>
 * 优先级高于ResourceServerConfigurer,用于保护oauth相关的endpoints,同时主要作用于用户的登录 form
 * login,Basic auth
 *
 * @author ygm
 */
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private OAuthProperties oauthProperties;
    @Autowired
    private UserDetailsService userDetailsService;

    /**
     * 加密方式<br/>
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

//    	@Bean
//	public UserDetailsManager userDetailsManager() {
//		UserDetails user = User.withUsername(oauthProperties.getLoginUser())
//				.passwordEncoder(new BCryptPasswordEncoder()::encode)
//				.password(oauthProperties.getLoginPassword())
//				.roles("admin")
//				.build();
//		return new InMemoryUserDetailsManager(user);
//	}

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                // .formLogin().and()
                .httpBasic().and().csrf().disable();
    }
}
